<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="视频标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入视频标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:videos:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:videos:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:videos:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:videos:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="作者" align="center" prop="nickname" width="80" />
      <el-table-column label="视频标题" align="center" prop="title" width="150" />
      <el-table-column label="视频描述" align="center" prop="description" width="200" />
      <el-table-column label="视频封面" align="center" prop="coverUrl" width="120">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.coverUrl"
            :src="scope.row.coverUrl" 
            :preview-src-list="[scope.row.coverUrl]"
            fit="cover"
            style="width: 100px; height: 60px; border-radius: 4px;">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <span v-else><i class="el-icon-picture-outline" style="font-size: 30px; color: #ccc;"></i></span>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="duration" width="80">
        <template slot-scope="scope">
          <el-tag size="small" type="info">{{ formatDuration(scope.row.duration) }}</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="视频时长(秒)" align="center" prop="duration" width="100" />-->
<!--      <el-table-column label="视频格式" align="center" prop="format" width="80" />-->
<!--      <el-table-column label="文件大小(字节)" align="center" prop="size" width="120" />-->
      <el-table-column label="标签" align="center" prop="tags" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.tags">
            <el-tag 
              v-for="(tag, index) in (scope.row.tags ? scope.row.tags.split(',').slice(0, 2) : [])" 
              :key="index" 
              size="mini"
              style="margin: 2px;">
              {{ tag.trim() }}
            </el-tag>
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryName" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.categoryName" size="small" effect="plain">
            {{ scope.row.categoryName }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="拍摄地点" align="center" prop="location" width="130" />
<!--      <el-table-column label="纬度" align="center" prop="latitude" width="100" />-->
<!--      <el-table-column label="经度" align="center" prop="longitude" width="100" />-->
      <el-table-column label="播放量" align="center" prop="viewCount" width="80">
        <template slot-scope="scope">
          <span><i class="el-icon-view"></i> {{ formatCount(scope.row.viewCount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点赞" align="center" prop="likeCount" width="70">
        <template slot-scope="scope">
          <span><i class="el-icon-star-off"></i> {{ formatCount(scope.row.likeCount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评论" align="center" prop="commentCount" width="70">
        <template slot-scope="scope">
          <span><i class="el-icon-chat-dot-round"></i> {{ formatCount(scope.row.commentCount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分享" align="center" prop="shareCount" width="70">
        <template slot-scope="scope">
          <span><i class="el-icon-share"></i> {{ formatCount(scope.row.shareCount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收藏" align="center" prop="collectCount" width="70">
        <template slot-scope="scope">
          <span><i class="el-icon-collection"></i> {{ formatCount(scope.row.collectCount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="私密" align="center" prop="isPrivate" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isPrivate === 1" size="small" type="warning">
            <i class="el-icon-lock"></i> 私密
          </el-tag>
          <el-tag v-else size="small" type="success">
            <i class="el-icon-unlock"></i> 公开
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.spff_video_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="150">
        <template slot-scope="scope">
          <span><i class="el-icon-time"></i> {{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:videos:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:videos:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="作者ID" prop="userId">-->
<!--          <el-input v-model="form.userId" placeholder="请输入作者ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="视频预览" prop="videoUrl">
          <div v-if="form.videoUrl" style="margin-top: 10px;">
            <video
              :src="form.videoUrl"
              :poster="form.coverUrl"
              controls
              preload="metadata"
              style="width: 100%; max-width: 400px; height: 250px; object-fit: cover; border-radius: 4px; border: 1px solid #dcdfe6;"
              @loadedmetadata="updateFormDuration($event)"
            >
              您的浏览器不支持视频播放
            </video>
            <div style="font-size: 12px; color: #909399; margin-top: 5px;">
              <i class="el-icon-video-play"></i> 时长: {{ formatDuration(form.duration) }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="视频封面" prop="coverUrl">
          <image-upload v-model="form.coverUrl"/>
        </el-form-item>
        <el-form-item label="作者" prop="nickname">
          <div>{{ form.nickname }}</div>
        </el-form-item>
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="分类ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入分类ID" />
        </el-form-item>
        <el-form-item label="拍摄地点" prop="location">
          <div>{{ form.location }}</div>
        </el-form-item>
<!--        <el-form-item label="纬度" prop="latitude">-->
<!--          <el-input v-model="form.latitude" placeholder="请输入纬度" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="经度" prop="longitude">-->
<!--          <el-input v-model="form.longitude" placeholder="请输入经度" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="播放次数" prop="viewCount">-->
<!--          <el-input v-model="form.viewCount" placeholder="请输入播放次数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="点赞数" prop="likeCount">-->
<!--          <el-input v-model="form.likeCount" placeholder="请输入点赞数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="评论数" prop="commentCount">-->
<!--          <el-input v-model="form.commentCount" placeholder="请输入评论数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="分享数" prop="shareCount">-->
<!--          <el-input v-model="form.shareCount" placeholder="请输入分享数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="收藏数" prop="collectCount">-->
<!--          <el-input v-model="form.collectCount" placeholder="请输入收藏数" />-->
<!--        </el-form-item>-->
        <el-form-item label="是否私密" prop="isPrivate">
          <el-select v-model="form.isPrivate" placeholder="请选择是否私密">
            <el-option
              v-for="dict in dict.type.spff_video_private"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态:0-删除,1-正常,2-审核中">
            <el-option
              v-for="dict in dict.type.spff_video_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="" prop="createdAt">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.createdAt"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="" prop="updatedAt">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.updatedAt"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-check" @click="submitForm">保 存</el-button>
        <el-button icon="el-icon-close" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVideos, getVideos, delVideos, addVideos, updateVideos } from "@/api/system/videos"

export default {
  name: "Videos",
  dicts: ['spff_video_private', 'spff_video_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频表格数据
      videosList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        location: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "作者ID不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "视频标题不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "视频文件URL不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询视频列表 */
    getList() {
      this.loading = true
      listVideos(this.queryParams).then(response => {
        this.videosList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        title: null,
        description: null,
        videoUrl: null,
        coverUrl: null,
        duration: null,
        width: null,
        height: null,
        format: null,
        size: null,
        tags: null,
        categoryId: null,
        location: null,
        latitude: null,
        longitude: null,
        viewCount: null,
        likeCount: null,
        commentCount: null,
        shareCount: null,
        collectCount: null,
        isPrivate: null,
        status: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加视频"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getVideos(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改视频"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVideos(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addVideos(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除视频编号为"' + ids + '"的数据项？').then(function() {
        return delVideos(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/videos/export', {
        ...this.queryParams
      }, `videos_${new Date().getTime()}.xlsx`)
    },
    /** 格式化视频时长 */
    formatDuration(duration) {
      if (!duration) return '未知'
      const minutes = Math.floor(duration / 60)
      const seconds = Math.floor(duration % 60)
      return `${minutes}:${seconds.toString().padStart(2, '0')}`
    },
    /** 更新视频时长 */
    updateDuration(row, event) {
      if (!row.duration && event.target.duration) {
        row.duration = Math.floor(event.target.duration)
      }
    },
    /** 更新表单中的视频时长 */
    updateFormDuration(event) {
      if (!this.form.duration && event.target.duration) {
        this.form.duration = Math.floor(event.target.duration)
      }
    },
    /** 格式化数字 */
    formatCount(count) {
      if (!count) return '0'
      if (count >= 10000) {
        return (count / 10000).toFixed(1) + 'w'
      }
      if (count >= 1000) {
        return (count / 1000).toFixed(1) + 'k'
      }
      return count.toString()
    }
  }
}
</script>

<style scoped>
/* 图片加载失败占位符 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 24px;
}
</style>
